package cn.tedu.oa.attendance.consumer;

import cn.tedu.oa.attendance.pojo.entity.BizData;
import cn.tedu.oa.attendance.pojo.entity.BizDataDetail;
import cn.tedu.oa.attendance.pojo.po.AttendancePO;
import cn.tedu.oa.attendance.service.AttendanceService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import shade.com.alibaba.fastjson2.JSONObject;

import java.time.LocalDateTime;

@Slf4j
@Component
public class DingDingConsumer implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    /**
     * 处理钉钉接收事件
     * @param eventType
     * @param bizData
     */
    public static void process(String eventType, JSONObject bizData) {
        log.debug("接收推送成功,类型是:{}",eventType);
        switch (eventType){
            case "attendance_check_record":
                log.debug("新增考勤打卡:{}",bizData);
                insertAttendance(bizData);
                break;
            case "attend_user_daily_summary_refresh":
                log.debug("查询考勤日打卡记录:{}",bizData);
                break;
            case "dingtalk.attendance.checkin.record.delete.push":
                log.debug("考勤打卡记录删除:{}",bizData);
        }
    }

    @Autowired
    private AttendanceService attendanceService;

    private static AttendancePO insertAttendance(JSONObject bizData) {
        ObjectMapper mapper = new ObjectMapper();
        BizData bizDataResult = null;
        try {
            bizDataResult = mapper.readValue(bizData.toString(), BizData.class);
            log.debug("考勤打卡数据#bizDataResult:{}",bizDataResult);
        } catch (JsonProcessingException e) {
            log.error("解析消息失败:{}",e);
        }
        BizDataDetail bizDataDetail = bizDataResult.getDataList().get(0);
        log.debug("考勤打卡数据#bizDataResult:{}",bizDataDetail);

        AttendancePO attendancePO = new AttendancePO();
        BeanUtils.copyProperties(bizDataDetail,attendancePO);

        AttendanceService attendanceService = applicationContext.getBean(AttendanceService.class);

        attendanceService.save(attendancePO);

        log.debug("考勤数据录入#attendancePO:{}",attendancePO);

        return attendancePO;

    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        DingDingConsumer.applicationContext = applicationContext;
    }
}
